import React, { useState } from 'react'
import './style/login.scss'
import { useNavigate } from 'react-router-dom'
import 'animate.css'
import axios from 'axios'
import { Toast } from 'antd-mobile'


export default function Forget() {
  let nav=useNavigate()
  let [tel, setTel] = useState('')
  let [code, setCode] = useState('')
  let [rcode, setrCode] = useState('')
  let [min, setMin] = useState(60)
  let [pwd,setPwd]=useState('')
  return (
    <div className='register'>
      <h1>忘记密码</h1>
          <div className='input'>
            <input value={tel} placeholder='手机号' onChange={(e)=>{setTel(e.target.value)}} onBlur={()=>{if(!/^1\d{10}$/.test(tel)){Toast.show({content:'手机号格式错误！'})} } }></input>
              <p className='Ycode'>
                  <input value={code} placeholder='验证码' onChange={(e) => { setCode(e.target.value) }}></input>
                  <button onClick={async() => {
                  let res = await axios.post('http://localhost:3000/zjj/get_sms', {tel})
                  if (res.data.code === 200) {
                    setrCode(res.data.sms)
                  } else {
                    console.log(res.data.msg);
                  }
                  let timer = setInterval(() => {
                      console.log(min);
                      setMin(min--)
                      if (min - 1 < 0) {
                        clearInterval(timer)
                        setMin(60)
                        }
                  },1000)
                  }} disabled={min!==60}>{(min===60||min===0)?'获取验证码':`${min}s重新获取` }</button>
              </p>
            <input value={pwd} placeholder='重置密码' onChange={(e)=>{setPwd(e.target.value)}}></input>
        <button className='animate__animated animate__slideInUp' disabled={!/^1\d{10}$/.test(tel)} onClick={async() => {
          if (code !== rcode) {
            Toast.show({
              content:'验证码错误！'
            })
            return false
          }
          let obj = {tel, pwd }
          let res = await axios.put('http://localhost:3000/zjj/forget', obj)
          if (res.data.code === 200) {
            Toast.show({
              content:'密码修改成功成功，将转跳到登录页'
            })

            nav('/login')
          } else {
            Toast.show({
              content:res.data.msg
            })
          }
            }}>保存账户密码</button>
          </div>
          <p className='footer'>没有账号？<span onClick={()=>{nav('/register')}}>去注册</span></p>
    </div>
  )
}
